<!DOCTYPE html>
<html>
<head>
    <title>页面新增</title>
    {% include 'system/common/header.html' %}</head>
    <link rel="stylesheet" href="{{ url_for('admin.static', filename='system/component/aieditor/style.css') }}"/>
    <style>

    </style>
<body>
<form class="layui-form" action="">
    <input type="hidden" name="type" id="article-type" value="rich">
    <div class="mainBox">
        <div class="main-container">
            <div class="main-container">
                <div class="layui-form-item">
                    <label class="layui-form-label">页面名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="title" lay-verify="required" autocomplete="off" placeholder="标签名称"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">页面别名</label>
                    <div class="layui-input-block">
                        <input type="text" name="slug" lay-verify="required" autocomplete="off" placeholder="别名"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">页面摘要</label>
                    <div class="layui-input-block">
                        <textarea placeholder="页面摘要" name="excerpt" class="layui-textarea"></textarea>
                    </div>
                </div>
                
                <!-- 特色图像 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">特色图像</label>
                    <div class="layui-input-block">
                        <div class="layui-row">
                            <div class="layui-col-md6">
                                <input type="text" name="featured_image" id="featured-image-url" placeholder="请输入图片地址或上传图片" class="layui-input">
                            </div>
                            <div class="layui-col-md6">
                                <button type="button" class="layui-btn layui-btn-primary" id="upload-featured-image">
                                    <i class="layui-icon layui-icon-upload"></i> 上传图片
                                </button>
                                <button type="button" class="layui-btn layui-btn-normal" id="paste-image-url">
                                    <i class="layui-icon layui-icon-link"></i> 粘贴地址
                                </button>
                            </div>
                        </div>
                        <div id="featured-image-preview" style="margin-top: 10px; display: none;">
                            <img id="preview-img" src="" alt="特色图像预览" style="max-width: 300px; max-height: 200px; border: 1px solid #e6e6e6; border-radius: 2px;">
                            <div style="margin-top: 5px;">
                                <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" id="remove-featured-image">
                                    <i class="layui-icon layui-icon-close"></i> 移除图片
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">页面内容</label>
                    <div class="layui-input-block">
                        <div id="editor" style="height: 550px"></div>
                    </div>
                </div>
                
                <!-- SEO信息 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">SEO标题</label>
                    <div class="layui-input-block">
                        <input type="text" name="meta_title" placeholder="SEO标题（可选）" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">SEO关键词</label>
                    <div class="layui-input-block">
                        <input type="text" name="meta_keywords" placeholder="SEO关键词，多个关键词用逗号分隔（可选）" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">SEO描述</label>
                    <div class="layui-input-block">
                        <textarea name="meta_description" placeholder="SEO描述（可选）" class="layui-textarea" style="height: 80px;"></textarea>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="layui-btn layui-btn-sm" lay-submit="" lay-filter="page-save">
                <i class="layui-icon layui-icon-ok"></i>
                草稿
            </button>
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" id="publish-btn">
                <i class="layui-icon layui-icon-release"></i>
                发布
            </button>
        </div>
    </div>
</form>
{% include 'system/common/footer.html' %}
<script src="{{ url_for('admin.static', filename='system/component/aieditor/index.js') }}"></script>
<script>
// 调试表单提交功能
console.log('=== 表单提交调试脚本 ===');

// 检查页面元素
console.log('检查页面元素...');
console.log('表单元素:', document.querySelector('form.layui-form'));
console.log('提交按钮:', document.querySelector('button[lay-filter="page-save"]'));

// 检查Layui是否加载
console.log('检查Layui...');
if (typeof layui !== 'undefined') {
    console.log('Layui已加载');
    console.log('Layui版本:', layui.v);
} else {
    console.error('Layui未加载');
}

// 检查jQuery是否加载
console.log('检查jQuery...');
if (typeof $ !== 'undefined') {
    console.log('jQuery已加载');
    console.log('jQuery版本:', $.fn.jquery);
} else {
    console.error('jQuery未加载');
}

// 手动绑定表单提交事件
console.log('手动绑定表单提交事件...');
document.addEventListener('DOMContentLoaded', function() {
    const submitBtn = document.querySelector('button[lay-filter="page-save"]');
    if (submitBtn) {
        console.log('找到提交按钮，添加点击事件监听器');
        submitBtn.addEventListener('click', function(e) {
            console.log('提交按钮被点击');
            e.preventDefault();
            
            // 获取表单数据
            const form = document.querySelector('form.layui-form');
            const formData = new FormData(form);
            const data = {};
            for (let [key, value] of formData.entries()) {
                data[key] = value;
            }
            
            console.log('表单数据:', data);
            
            // 获取编辑器内容
            let editorContent = '';
            
            // 首先尝试从DOM获取内容
            const editorElement = document.querySelector('#editor');
            if (editorElement) {
                const contentElement = editorElement.querySelector('[contenteditable="true"]') || 
                                      editorElement.querySelector('.ai-editor-content') ||
                                      editorElement.querySelector('.editor-content') ||
                                      editorElement;
                
                if (contentElement) {
                    editorContent = contentElement.innerHTML;
                    console.log('从DOM获取到编辑器内容:', editorContent);
                }
            }
            
            // 如果DOM内容为空，尝试使用AiEditor API
            if (!editorContent && window.aiEditor) {
                try {
                    if (typeof window.aiEditor.getContent === 'function') {
                        editorContent = window.aiEditor.getContent();
                    } else if (typeof window.aiEditor.getHtml === 'function') {
                        editorContent = window.aiEditor.getHtml();
                    } else if (typeof window.aiEditor.getMarkdown === 'function') {
                        editorContent = window.aiEditor.getMarkdown();
                    } else if (typeof window.aiEditor.getText === 'function') {
                        editorContent = window.aiEditor.getText();
                    }
                    console.log('从AiEditor API获取到内容:', editorContent);
                } catch (error) {
                    console.error('AiEditor API调用失败:', error);
                }
            }
            
            if (!editorContent) {
                console.warn('无法获取编辑器内容');
            }
            
            // 构建提交数据
            const submitData = {
                title: data.title,
                slug: data.slug,
                excerpt: data.excerpt,
                content: editorContent,
                meta_title: data.meta_title || '',
                meta_keywords: data.meta_keywords || '',
                meta_description: data.meta_description || '',
                status: 'draft'
            };
            
            console.log('准备提交的数据:', submitData);
            
            // 发送AJAX请求
            if (typeof $ !== 'undefined') {
                $.ajax({
                    url: '/admin/cms/page/save',
                    data: JSON.stringify(submitData),
                    dataType: 'json',
                    contentType: 'application/json',
                    type: 'post',
                    success: function(result) {
                        console.log('请求成功:', result);
                        if (result.success) {
                            alert('保存成功: ' + result.msg);
                        } else {
                            alert('保存失败: ' + result.msg);
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('请求失败:', xhr, status, error);
                        alert('保存失败: ' + error);
                    }
                });
            } else {
                console.error('jQuery未加载，无法发送AJAX请求');
            }
        });
    } else {
        console.error('未找到提交按钮');
    }
});

console.log('调试脚本加载完成');

// 绑定事件
layui.use(['form', 'jquery'], function() {
    let $ = layui.jquery;

    // 特色图像功能
    // 上传图片
    $('#upload-featured-image').click(function() {
        // 创建一个隐藏的文件输入框
        let fileInput = $('<input type="file" accept="image/*" style="display: none;">');
        $('body').append(fileInput);
        
        fileInput.click();
        
        fileInput.on('change', function() {
            let file = this.files[0];
            if (file) {
                // 创建FormData对象
                let formData = new FormData();
                formData.append('image', file);
                formData.append('type', 'images');
                
                // 上传文件
                $.ajax({
                    url: '/admin/cms/page/upload',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(result) {
                        if (result.errorCode === 0) {
                            let imageUrl = result.data.src;
                            $('#featured-image-url').val(imageUrl);
                            showImagePreview(imageUrl);
                            layer.msg('图片上传成功', {icon: 1});
                        } else {
                            layer.msg(result.msg || '上传失败', {icon: 2});
                        }
                    },
                    error: function() {
                        layer.msg('上传失败', {icon: 2});
                    }
                });
            }
            
            // 移除临时文件输入框
            fileInput.remove();
        });
    });
    
    // 粘贴图片地址
    $('#paste-image-url').click(function() {
        layer.prompt({
            title: '请输入图片地址',
            formType: 0,
            value: '',
            area: ['400px', '150px']
        }, function(value, index) {
            if (value && value.trim()) {
                $('#featured-image-url').val(value.trim());
                showImagePreview(value.trim());
                layer.close(index);
                layer.msg('图片地址已设置', {icon: 1});
            } else {
                layer.msg('请输入有效的图片地址', {icon: 2});
            }
        });
    });
    
    // 移除特色图像
    $('#remove-featured-image').click(function() {
        $('#featured-image-url').val('');
        $('#featured-image-preview').hide();
        layer.msg('特色图像已移除', {icon: 1});
    });
    
    // 显示图片预览
    function showImagePreview(imageUrl) {
        if (imageUrl && imageUrl.trim()) {
            $('#preview-img').attr('src', imageUrl);
            $('#featured-image-preview').show();
        } else {
            $('#featured-image-preview').hide();
        }
    }
    
    // 监听图片地址输入框变化
    $('#featured-image-url').on('input', function() {
        let imageUrl = $(this).val().trim();
        showImagePreview(imageUrl);
    });
    
    // 初始化特色图像预览（如果有值）
    let initialImageUrl = $('#featured-image-url').val();
    if (initialImageUrl) {
        showImagePreview(initialImageUrl);
    }
});

</script>
    <script type="module">
        import {AiEditor} from "{{ url_for('admin.static', filename='system/component/aieditor/index.js') }}";
        
        // 等待DOM加载完成后初始化AiEditor
        document.addEventListener('DOMContentLoaded', function() {
            window.aiEditor = new AiEditor({
                element: "#editor",
                placeholder: "点击输入内容...",
                content: '',
            image: {
                allowBase64: false,
                defaultSize: 350,
                uploadUrl: "/admin/cms/page/upload",
                uploadFormName: "image", //上传时的文件表单名称
                uploaderEvent: {
                    onUploadBefore: (file, uploadUrl, headers) => {
                        //监听图片上传之前，此方法可以不用回任何内容，但若返回 false，则终止上传
                        console.log('图片上传开始:', file.name);
                    },
                    onSuccess: (file, response) => {
                        //监听图片上传成功
                        console.log('图片上传成功:', response);
                        //注意：
                        // 1、如果此方法返回 false，则图片不会被插入到编辑器
                        // 2、可以在这里返回一个新的 json 给编辑器
                    },
                    onFailed: (file, response) => {
                        //监听图片上传失败，或者返回的 json 信息不正确
                        console.error('图片上传失败:', response);
                    },
                    onError: (file, error) => {
                        //监听图片上传错误，比如网络超时等
                        console.error('图片上传错误:', error);
                    },
                },
                bubbleMenuItems: ["AlignLeft", "AlignCenter", "AlignRight", "delete"]
            },
            video: {
                uploadUrl: "/admin/cms/page/upload",
                uploadFormName: "video", //上传时的文件表单名称
                uploaderEvent: {
                    onUploadBefore: (file, uploadUrl, headers) => {
                        //监听视频上传之前，此方法可以不用回任何内容，但若返回 false，则终止上传
                        console.log('视频上传开始:', file.name);
                    },
                    onSuccess: (file, response) => {
                        //监听视频上传成功
                        console.log('视频上传成功:', response);
                        //注意：
                        // 1、如果此方法返回 false，则视频不会被插入到编辑器
                        // 2、可以在这里返回一个新的 json 给编辑器
                    },
                    onFailed: (file, response) => {
                        //监听视频上传失败，或者返回的 json 信息不正确
                        console.error('视频上传失败:', response);
                    },
                    onError: (file, error) => {
                        //监听视频上传错误，比如网络超时等
                        console.error('视频上传错误:', error);
                    },
                }
            },
            attachment: {
                uploadUrl: "/admin/cms/page/upload",
                uploadFormName: "attachment", //上传时的文件表单名称
                uploaderEvent: {
                    onUploadBefore: (file, uploadUrl, headers) => {
                        //监听附件上传之前，此方法可以不用回任何内容，但若返回 false，则终止上传
                        console.log('附件上传开始:', file.name);
                    },
                    onSuccess: (file, response) => {
                        //监听附件上传成功
                        console.log('附件上传成功:', response);
                        //注意：
                        // 1、如果此方法返回 false，则附件不会被插入到编辑器
                        // 2、可以在这里返回一个新的 json 给编辑器
                    },
                    onFailed: (file, response) => {
                        //监听附件上传失败，或者返回的 json 信息不正确
                        console.error('附件上传失败:', response);
                    },
                    onError: (file, error) => {
                        //监听附件上传错误，比如网络超时等
                        console.error('附件上传错误:', error);
                    },
                }
            },
            ai: {
                models: {
                    spark: {
                        appId: "***",
                        apiKey: "***",
                        apiSecret: "***",
                    }
                }
            },
        });
        });
    </script>
<script>
  layui.use(['form', 'jquery'], function () {
    let form = layui.form
    let $ = layui.jquery
    
    console.log('Layui form 初始化完成');
    console.log('Form对象:', form);
    console.log('jQuery对象:', $);

    // 获取URL参数并设置页面类型
    function getUrlParameter(name) {
      name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
      var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
      var results = regex.exec(location.search);
      return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
    }
    
    // 设置页面类型
    var articleType = getUrlParameter('type') || 'rich';
    $('#article-type').val(articleType);
    console.log('页面类型:', articleType);

    // 测试表单事件绑定
    console.log('绑定表单提交事件...');
    // 草稿按钮事件处理
    form.on('submit(page-save)', function (data) {
      console.log('草稿按钮事件触发', data);
      
      // 获取AiEditor的内容
      let editorContent = '';
      
      // 首先尝试从DOM获取内容（最可靠的方法）
      const editorElement = document.querySelector('#editor');
      if (editorElement) {
        // 查找编辑器内的内容区域
        const contentElement = editorElement.querySelector('[contenteditable="true"]') || 
                              editorElement.querySelector('.ai-editor-content') ||
                              editorElement.querySelector('.editor-content') ||
                              editorElement;
        
        if (contentElement) {
          editorContent = contentElement.innerHTML;
          console.log('从DOM获取到编辑器内容:', editorContent);
        }
      }
      
      // 如果DOM内容为空，尝试使用AiEditor API
      if (!editorContent && window.aiEditor) {
        try {
          if (typeof window.aiEditor.getContent === 'function') {
            editorContent = window.aiEditor.getContent();
          } else if (typeof window.aiEditor.getHtml === 'function') {
            editorContent = window.aiEditor.getHtml();
          } else if (typeof window.aiEditor.getMarkdown === 'function') {
            editorContent = window.aiEditor.getMarkdown();
          } else if (typeof window.aiEditor.getText === 'function') {
            editorContent = window.aiEditor.getText();
          }
          console.log('从AiEditor API获取到内容:', editorContent);
        } catch (error) {
          console.error('AiEditor API调用失败:', error);
        }
      }
      
      if (!editorContent) {
        console.warn('无法获取编辑器内容');
      }
      
      // 构建提交数据
      let submitData = {
        title: data.field.title,
        slug: data.field.slug,
        excerpt: data.field.excerpt,
        featured_image: data.field.featured_image || '',
        content: editorContent,
        meta_title: data.field.meta_title || '',
        meta_keywords: data.field.meta_keywords || '',
        meta_description: data.field.meta_description || '',
        type: data.field.type || 'rich',  // 页面类型
        status: 'draft'  // 保存为草稿
      }
      
      console.log('准备提交的数据:', submitData);
      console.log('提交URL:', '/admin/cms/page/save');
      
      $.ajax({
        url: '/admin/cms/page/save',
        data: JSON.stringify(submitData),
        dataType: 'json',
        contentType: 'application/json',
        type: 'post',
        success: function (result) {
          if (result.success) {
            layer.msg(result.msg, { icon: 1, time: 1000 }, function () {
              parent.layer.close(parent.layer.getFrameIndex(window.name))//关闭当前页
              parent.layui.table.reload('page-table')  // 修正表格名称
            })
          } else {
            layer.msg(result.msg, { icon: 2, time: 1000 })
          }
        },
        error: function (xhr, status, error) {
          layer.msg('保存失败: ' + error, { icon: 2, time: 2000 })
        }
      })
      return false
    })
    
    // 发布按钮事件处理
    $('#publish-btn').click(function() {
      console.log('发布按钮事件触发');
      
      // 获取表单数据 - 使用与草稿按钮相同的方式
      let formData = {};
      $('form.layui-form input, form.layui-form textarea, form.layui-form select').each(function() {
        let name = $(this).attr('name');
        let value = $(this).val();
        if (name) {
          formData[name] = value;
        }
      });
      
      console.log('获取到的表单数据:', formData);
      
      // 获取AiEditor的内容
      let editorContent = '';
      
      // 首先尝试从DOM获取内容（最可靠的方法）
      const editorElement = document.querySelector('#editor');
      if (editorElement) {
        // 查找编辑器内的内容区域
        const contentElement = editorElement.querySelector('[contenteditable="true"]') || 
                              editorElement.querySelector('.ai-editor-content') ||
                              editorElement.querySelector('.editor-content') ||
                              editorElement;
        
        if (contentElement) {
          editorContent = contentElement.innerHTML;
          console.log('从DOM获取到编辑器内容:', editorContent);
        }
      }
      
      // 如果DOM内容为空，尝试使用AiEditor API
      if (!editorContent && window.aiEditor) {
        try {
          if (typeof window.aiEditor.getContent === 'function') {
            editorContent = window.aiEditor.getContent();
          } else if (typeof window.aiEditor.getHtml === 'function') {
            editorContent = window.aiEditor.getHtml();
          } else if (typeof window.aiEditor.getMarkdown === 'function') {
            editorContent = window.aiEditor.getMarkdown();
          } else if (typeof window.aiEditor.getText === 'function') {
            editorContent = window.aiEditor.getText();
          }
          console.log('从AiEditor API获取到内容:', editorContent);
        } catch (error) {
          console.error('AiEditor API调用失败:', error);
        }
      }
      
      if (!editorContent) {
        console.warn('无法获取编辑器内容');
      }
      
              // 构建提交数据
        let submitData = {
            title: formData.title,
            slug: formData.slug,
            excerpt: formData.excerpt,
            featured_image: formData.featured_image || '',
            content: editorContent,
            meta_title: formData.meta_title || '',
            meta_keywords: formData.meta_keywords || '',
            meta_description: formData.meta_description || '',
            type: formData.type || 'rich',  // 页面类型
            status: 'published'  // 发布状态
        }
      
      console.log('准备发布的数据:', submitData);
      console.log('发布URL:', '/admin/cms/page/save');
      
      $.ajax({
        url: '/admin/cms/page/save',
        data: JSON.stringify(submitData),
        dataType: 'json',
        contentType: 'application/json',
        type: 'post',
        success: function (result) {
          if (result.success) {
            layer.msg(result.msg, { icon: 1, time: 1000 }, function () {
              parent.layer.close(parent.layer.getFrameIndex(window.name))//关闭当前页
              parent.layui.table.reload('page-table')  // 修正表格名称
            })
          } else {
            layer.msg(result.msg, { icon: 2, time: 1000 })
          }
        },
        error: function (xhr, status, error) {
          layer.msg('发布失败: ' + error, { icon: 2, time: 2000 })
        }
      })
    })
  })
</script>

</body>
</html>